package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);

        if (success){
            //2.添加任务到redis
            addTasktoCache(task);
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        //删除任务，更新日志
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);

        //删除redis中的任务
        if (task != null){
            removeTaskFromCache(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            String key = type + "_" + priority;
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            task = JSON.parseObject(task_json, Task.class);
            //修改数据库信息
            if(task != null){
                updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e){
            e.printStackTrace();
            log.error("poll task exception");
        }
        return task;
    }

    /**
     * 数据库任务定时同步到redis
     */
    @PostConstruct  //黑机启动
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        //清理缓存
        clearCach();
        //查出未来五分钟的所有任务
        List<Taskinfo> list = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime,new Date(System.currentTimeMillis()+1000*60*5)));
        //将任务添加到redis中
        if (!list.isEmpty() && list != null){
            for (Taskinfo taskinfo : list) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTasktoCache(task);
            }
        }
        log.info("数据库的任务同步到了redis");
    }

    /**
     * 删除redis中未来数据集合和当前消费者队列的所有key
     */
    private void clearCach() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }

    /**
     * 未来任务定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)){
            log.info("未来任务定时刷新 --- 定时任务开始");
            long start = System.currentTimeMillis() / 1000;

            //获取所有未来任务
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE+"*");
            for (String futureKey : futureKeys) {
                //设置当前需要执行的任务key
                String topicKey = ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取当前需要执行的任务
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                //同步任务
                if (!tasks.isEmpty() && tasks != null){
                    cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                }
                log.info("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
            }

            long end = System.currentTimeMillis() / 1000;
            log.info("未来任务定时刷新 --- 定时任务结束，耗时: " + String.valueOf(end-start) + "秒");
        }
    }

    /**
     * 删除redis中的任务
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();

        if (task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }
        else if (task.getExecuteTime() > System.currentTimeMillis()
                && task.getExecuteTime() <= nextScheduleTime){
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }
    }

    /**
     * 更新任务
     * @param taskId
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task = null;
        try {
            //1.删除任务信息
            taskinfoMapper.deleteById(taskId);

            //2.更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status); //修改状态
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e){log.error("task cancel exception taskid:{}",taskId);}

        return task;
    }

    /**
     * 添加任务到redis中
     * @param task
     */
    private void addTasktoCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取5分钟之后的时间  毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();

        //需要立即执行的任务存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }
        //未来五分钟内执行的任务存入set
        else if (task.getExecuteTime() > System.currentTimeMillis()
                   && task.getExecuteTime() <= nextScheduleTime){
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean success = false;

        try {
            //保存任务信息
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            task.setTaskId(taskinfo.getTaskId()); //设置dto的taskId

            //保存任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task,taskinfoLogs);
            taskinfoLogs.setExecuteTime(taskinfo.getExecuteTime());
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED); //设置初始状态
            taskinfoLogs.setVersion(1); //设置版本号
            taskinfoLogsMapper.insert(taskinfoLogs);
            success = true;
        } catch (Exception e){e.printStackTrace();}

        return success;
    }
}
